﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using System.Diagnostics;

namespace Cngot.Extensions.Logger
{
    internal class HttpContextHeaderMessageHandler : DelegatingHandler
    {
        private readonly IHttpContextAccessor _contextAccessor;
        private readonly IConfiguration _configuration;
        //private static string[] headerKeys = new string[] {
        //    HeaderNames.UserAgent,
        //    HeaderNames.Authorization,
        //    HeaderNames.CorrelationContext,

        //};
        public HttpContextHeaderMessageHandler(IServiceProvider serviceProvider, IConfiguration configuration)
        {
            _contextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
            _configuration = configuration;
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (!request.Headers.Contains(HeaderNames.TraceParent))
            {
                //解决NET8 traceparent 不透传问题
                request.Headers.TryAddWithoutValidation(HeaderNames.TraceParent, Activity.Current.Id);
            }
            request.Headers.TryAddWithoutValidation("X-AppId", _configuration.GetValue<string>("Apollo:AppId"));
            //if (_contextAccessor != null && _contextAccessor.HttpContext != null)
            //{
            //    foreach (var key in headerKeys)
            //    {
            //        if (!request.Headers.Contains(key) && _contextAccessor.HttpContext.Request.Headers.TryGetValue(key, out var value))
            //        {
            //            request.Headers.Add(key, value.ToList());
            //        }
            //    }
            //}

            return base.SendAsync(request, cancellationToken);
        }
    }
}
